package utils

import (
	"context"
	"github.com/FISCO-BCOS/go-sdk/client"
	"github.com/FISCO-BCOS/go-sdk/conf"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var (
	Instance *client.Client
	Db       *gorm.DB
	MongoDb  *mongo.Client
)

//初始化
func init() {
	configFile, err := conf.ParseConfigFile("config/config.toml")
	if err != nil {
		log.Println("failed to parse config:", err.Error())
	}
	config := configFile[0]
	Instance, err = client.Dial(&config)
	if err != nil {
		log.Println("failed to dial:", err.Error())
	}

	//数据库连接

	ReadDB()
	data := viper.GetString("username") + ":" + viper.GetString("password") + "@tcp(" + viper.GetString("host") + ":" + viper.GetString("port") + ")/" + viper.GetString("database") + "?charset=utf8mb4&parseTime=True&loc=Local"

	Db, err = gorm.Open("mysql", data)

	Db.DB().SetMaxOpenConns(100) //最大连接数
	Db.DB().SetMaxIdleConns(50)  //最大空闲数

	//进行mongo连接
	clientOptions := options.Client().ApplyURI("mongodb://43.138.147.44:27017")

	// 连接到MongoDB
	MongoDb, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
}

func ReadDB() {
	viper.SetConfigFile("./config/database.json")
	viper.SetConfigName("./database")
	viper.SetConfigType("json")
	viper.AddConfigPath("./config")
	viper.ReadInConfig()
}
